import router from '@/router';
import website from '@/config/website';
import { useUserStoreHook } from '@/stores/user';
import { useMenuStoreHook } from '@/stores/user/menu';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({ showSpinner: false });

// 动态路由加载状态
let isDynamicRouteAdded = false;

router.beforeEach(async (to, from, next) => {
    const { accessToken } = useUserStoreHook();
    if (!accessToken) {
        if (website.routeWhiteList.includes(to.path)) return next();
        next('/login');
        return;
    }
    if (to.path === '/login') return next('/home');
    if (!isDynamicRouteAdded) {
        try {
            const menuStore = useMenuStoreHook();
            await menuStore.storeGetRoutes();
            isDynamicRouteAdded = true;
            // 跳转到目标路由
            next({ ...to, replace: true });
        } catch (error) {
            console.error('Failed to get routes:', error);
            // 获取路由失败时跳转登录页
            next(`/login?redirect=${to.path}`);
        }
    } else {
        next();
    }
});
router.afterEach((to, from) => {
    document.title = `${String(to.name)}-${website.title}`;
    NProgress.done();
});
